local UIHeroPopularityRank = UIBase.New(PanelResNames.UIHeroPopularityRank)

local panel         = UIHeroPopularityRank

local m_rank_list   = {}
local m_job_type    = nil
local m_hot_list    = {}
local m_renqi_list  = {}
local m_hot_server  = {}
local m_chapter_type = 1

local m_chapter_btn = {}

local m_temp_job = {1, 4, 6, 2, 3, 5}
local m_version = 0

function panel.Init(data)
    UIBase.Init(UIHeroPopularityRank)
end

local list_sort = function(a,b)
    if a.score ~= b.score then
        return a.score > b.score
    else
        if a.sort ~= b.sort then
            return a.sort > b.sort
        end
    end
    return a.heroId < b.heroId
end

function panel:OnCreate()
    self.scroll_list    = self:GetChild("list")
    self.bgClose        = self:GetChild("bgClose")
    self.btnClose       = self:GetChild("btnClose")
    self.ctr_herotype   = self:GetController("ctrlHeroType")
    self.ctr_type       = self:GetController("type")
    self.btn_change     = self:GetChild("Btn_Range")
    self.pageHot        = self:GetChild("pageHot")

    self.ctr_chapter    = self.btn_change:GetController("Type")

    self.txt_title      = self:GetChild("title")
    self.chaptergroup   = self:GetChild("n79")
    self.ctr_level      = self:GetController("levelchioce") 
    m_chapter_btn["btn_chapter1"] = self.chaptergroup :GetChild("Btn_WinRate")
    m_chapter_btn["btn_chapter2"] = self.chaptergroup :GetChild("Btn_ShowRate")
    m_chapter_btn["btn_chapter3"] = self.chaptergroup :GetChild("Btn_BanRate")
    m_chapter_btn["btn_chapter4"] = self.chaptergroup :GetChild("Btn_RankChange")

    for i=1, 4 do
        m_chapter_btn["btn_chapter" .. i].onClick:Add(function()
            panel.onSelectChapter(i)
        end)
    end

    self:RegisterOnClick(self:GetChild("bgClose"), self.ClosePanel)
    self:RegisterOnClick(self:GetChild("btnClose"), self.ClosePanel)

    self.ctr_type.onChanged:Add(panel.onTypeChanged)

    self.ctr_herotype.onChanged:Add(function()
        local index = self.ctr_herotype.selectedIndex

        panel:onJobChanged(m_temp_job[index])
    end)

    self.scroll_list.itemRenderer =function(index,obj)
        panel:RankItemRender(index,obj)
    end

    m_renqi_list = {}
    local heroCfg = G.dataTable["t_hero"]
    for k,v in pairs(heroCfg) do
        if (v.f_Type == "" or v.f_Type == 0) and v.f_Version ~= 2 and logicMgr.HeroManager.isOpenHeroAtlas(v.f_HeroID) then
            table.insert(m_renqi_list, {heroId = v.f_HeroID, score = 0, sort = 0})
        end
    end
    table.sort(m_renqi_list, list_sort)

    m_hot_list = {}
    local heroCfg = G.dataTable["t_hero"]
    for k,v in pairs(heroCfg) do
        if (v.f_Type == "" or v.f_Type == 0) and v.f_Version ~= 2 and logicMgr.HeroManager.isOpenHeroAtlas(v.f_HeroID) then
            table.insert(m_hot_list, {heroId = v.f_HeroID, score = 0, sort = 0})
        end
    end
    table.sort(m_hot_list, list_sort)
    
    -- self.scroll_list.numItems = #m_renqi_list
end

function panel:OnEnable()
    ListenEvent(Config.EventType.UpdateHeroCommentRank, panel.PopularityRefresh)
    ListenEvent(Config.EventType.UpdateHeroHotRank, panel.HotRankRefresh)
    ListenEvent(Config.EventType.UpdateLikeHero, partnerHandler.Req_HeroCommentRanks)

    partnerHandler.Req_HeroCommentRanks()
    partnerHandler.Req_HeroHotRanks(1)
    self.ctr_type.selectedIndex = 1
    self.ctr_type.selectedIndex = 0
    self:onTypeChanged()
    
    -- self.pageHot.displayObject.gameObject:SetActive(false)
    -- self.pageHot.visible = false
end

function panel.HotRankRefresh(tb)
    logicMgr.HeroManager.SetHotHeroRank(tb)

    local serverlist = HeroManager.GetHotHeroRank(tb.rankType)

    if m_hot_server[tb.rankType] == nil then
        m_hot_server[tb.rankType] = clone(m_hot_list)
    end

    local ls = m_hot_server[tb.rankType]
    for k,v in pairs(serverlist) do
        for i=1, #ls do
            if v.heroModeId == ls[i].heroId then
                ls[i].score = v.score
                break
            end
        end
    end
    table.sort(m_hot_server[tb.rankType], list_sort)

    if panel.ctr_type.selectedIndex == 0 then
        m_rank_list = m_hot_server[tb.rankType]
        panel.scroll_list.numItems = #m_rank_list
        panel.ctr_herotype.selectedIndex = 0

        -- self.scroll_list:ScrollToView(0)
    end
end

function panel.PopularityRefresh(list)
    local sort = #list
    for i=1, #list do
        for k,v in pairs(m_renqi_list) do
            if v.heroId == list[i].heroId then
                v.score = tonumber(tostring(list[i].score))
                v.sort = sort
                sort = sort - 1
                break
            end
        end
    end
    table.sort(m_renqi_list, list_sort)

    if panel.ctr_type.selectedIndex == 1 then
        m_rank_list = m_renqi_list
        panel.scroll_list.numItems = #m_renqi_list
    end
end

function panel:RankItemRender(index, obj)
    local data = m_rank_list[index + 1]

    local txt_name = obj:GetChild("name")
    local txt_rank = obj:GetChild("rank")
    local txt_point = obj:GetChild("point")
    local ctr_rank = obj:GetController("rank")
    local obj_hero = obj:GetChild("hero")
    local txt_nickname = obj:GetChild("nickname")
    local ctr_ranktype = obj:GetController("ranktype")
    
    if index < 3 then
        ctr_rank.selectedIndex = index
    else
        ctr_rank.selectedIndex = 3
    end
    ctr_ranktype.selectedIndex = panel.ctr_type.selectedIndex

    local hero = HeroManager.getHeroDatabyModelId(data.heroId)
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem)
    ctrlItem.initData(obj_hero, hero, nil, nil, nil, nil, nil, true)
    obj.touchable = false
    obj.onClick:Clear()
    if self.ctr_type.selectedIndex == 1 then
        obj.touchable = true
        obj.onClick:Add(function()
            showUI(PanelNames.UICharactorInfoArchives, hero, 2);
        end)
    end
    txt_rank.text = index + 1
    txt_point.text = getNumString(tonumber(tostring(data.score)))
    txt_name.text = logicMgr.HeroManager.GetHeroNameByModelId(data.heroId)
    txt_nickname.text = logicMgr.HeroManager.GetHeroSubnameByModelId(data.heroId)
end

function panel:OnDisable()
    CloseEvent(Config.EventType.UpdateHeroCommentRank, panel.PopularityRefresh)
    CloseEvent(Config.EventType.UpdateHeroHotRank, panel.HotRankRefresh)
    CloseEvent(Config.EventType.UpdateLikeHero, partnerHandler.Req_HeroCommentRanks)
end

function panel:ClosePanel()
    closeUI(PanelResNames.UIHeroPopularityRank)
end

function panel:onTypeChanged()
    panel.ctr_herotype.selectedIndex = 0
    if panel.ctr_type.selectedIndex == 1 then
        panel.txt_title.text = getLanguage("HotRankTitle2")
        m_rank_list = m_renqi_list
        panel.scroll_list.numItems = #m_renqi_list
    else
        panel.txt_title.text = getLanguage("HotRankTitle1")

        m_rank_list = m_hot_server[m_chapter_type] or {}
        panel.scroll_list.numItems = #m_rank_list
    end
end

function panel:onJobChanged(job)
    job = job or 0
    m_rank_list = panel:GetRankList(panel.ctr_type.selectedIndex, job)
    panel.scroll_list.numItems = #m_rank_list
end

function panel:FilterType(list, job)
    local ls = {}
    local h
    for k,v in pairs(list) do
        h = HeroManager.getHeroDatabyModelId(v.heroId)
        if h.type == job then
            table.insert(ls, v)
        end
    end
    return ls
end

function panel:GetRankList(type, job)
    if type == 1 then
        if job == 0 then
            return m_renqi_list
        else
            return panel:FilterType(m_renqi_list, job)
        end
    else
        if job == 0 then
            return m_hot_server[m_chapter_type]
        else
            return panel:FilterType(m_hot_server[m_chapter_type], job)
        end
    end
end

function panel.onSelectChapter(type)
    m_chapter_type = type

    if m_hot_server[type] == nil then
        m_hot_server[type] = clone(m_hot_list)
        partnerHandler.Req_HeroHotRanks(type)
    else
        m_rank_list = m_hot_server[type]
        panel.scroll_list.numItems = #m_rank_list
        panel.ctr_herotype.selectedIndex = 0

        panel.scroll_list:ScrollToView(0)
    end
    
    panel.ctr_level.selectedIndex = 0
    panel.ctr_chapter.selectedIndex = type - 1
end

return panel